from django.contrib import admin

from apps.rbac.models import Menu, Operate, MenuOperate, SensitiveField, MenuSensitiveField, \
    UserMenuSensitiveField, MenuOperateUrls


class MenuOperateUrlsInline(admin.TabularInline):
    model = MenuOperateUrls
    verbose_name = "操作URL"
    verbose_name_plural = "操作URLs"
    extra = 1  # 默认显示1个空表单
    fields = ('description', 'url', 'method', 'is_active')


class MenuOperateInline(admin.TabularInline):
    model = MenuOperate
    verbose_name = "菜单操作"
    verbose_name_plural = "菜单操作"
    extra = 1
    raw_id_fields = ('operate',)  # 保留raw_id跳转功能
    fields = ('operate', 'is_node',)
    autocomplete_fields = ('operate',)
    inlines = [MenuOperateUrlsInline]  # 嵌套URL内联表单


@admin.register(Menu)
class MenuAdmin(admin.ModelAdmin):
    list_display = ('code', 'name', 'name_en', 'parent', 'is_active', 'sort_rule')
    search_fields = ('name', 'code', 'content')
    list_filter = ('is_active', 'is_green_light')
    fieldsets = (
        ('基本信息', {
            'fields': ('parent', 'code', 'name', 'name_en', 'content', 'sort_rule', 'is_active', 'is_green_light')
        }),
    )
    # 将AMPMenuCustomize作为内联表单添加
    inlines = [
        MenuOperateInline
    ]


@admin.register(Operate)
class OperateAdmin(admin.ModelAdmin):
    list_display = ('code', 'name', 'name_en')
    search_fields = ('code', 'name')


@admin.register(MenuOperate)
class MenuOperateAdmin(admin.ModelAdmin):
    list_display = ('menu', 'operate', 'is_node')

    fieldsets = (
        (None, {'fields': ('menu', 'operate', 'is_node')}),
    )

    list_filter = ('menu',)
    search_fields = ['menu']
    # raw_id_fields = ('menu', 'operate')
    autocomplete_fields = ('menu', 'operate')  # 使用autocomplete代替raw_id
    inlines = [MenuOperateUrlsInline]  # 单独管理时也可编辑URL

    # 自定义列表显示，显示code和name
    def menu_code_name(self, obj):
        return f"{obj.menu.code} - {obj.menu.name}"

    menu_code_name.short_description = "菜单"

    def operate_code_name(self, obj):
        return f"{obj.operate.code} - {obj.operate.name}"

    operate_code_name.short_description = "操作"


@admin.register(MenuOperateUrls)
class MenuOperateUrlsAdmin(admin.ModelAdmin):
    list_display = ('description', 'url', 'method')
    list_filter = ('description',)
    fieldsets = (
        (None, {'fields': ('menu_operate', 'description', 'url', 'method')}),
    )
    search_fields = ['description']


@admin.register(SensitiveField)
class SensitiveFieldAdmin(admin.ModelAdmin):
    list_display = ('code', 'name', 'name_en', 'field_type')


@admin.register(MenuSensitiveField)
class MenuSensitiveFieldAdmin(admin.ModelAdmin):
    list_display = ('menu', 'sensitive_field')
    list_filter = ('menu',)
    search_fields = ['menu']


@admin.register(UserMenuSensitiveField)
class UserMenuSensitiveFieldAdmin(admin.ModelAdmin):
    list_display = ('user', 'menu_sensitive_field', 'permission_type')
    list_filter = ('user',)
    search_fields = ['user']
